package com.mystore.servlet;

import com.mystore.entity.User;
import com.mystore.service.CartService;
import com.mystore.service.impl.CartServiceImpl;
import com.mystore.util.CartUtil;
import com.mystore.vo.GoodVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/check/cart/*")
public class CartServlet extends HttpServlet {
    CartService cartService = new CartServiceImpl();
    CartUtil cartUtil = CartUtil.getInstance();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String method = uri.replace(request.getContextPath() + "/check/cart/", "");
        System.out.println("method=" + method);
        PrintWriter out = response.getWriter();
        User user = (User) request.getSession().getAttribute(UserServlet.USER);
        int uid = user.getId();
        HttpSession session = request.getSession();
        String url = "";

        cartUtil = (CartUtil) session.getAttribute(UserServlet.CART);

        switch (method) {
            case "addCart"://添加到购物车
                int gid = Integer.parseInt(request.getParameter("gid"));
                GoodVO goodVO = (GoodVO) session.getAttribute(String.valueOf(gid));
                if (cartUtil.isContains(gid)) {//如果已经存在,则取出来加1
                    GoodVO goodVO1 = (GoodVO) cartUtil.getValue(gid);
                    goodVO1.setNum(goodVO1.getNum() + 1);
                } else {//如果不存在,则新增
                    goodVO.setNum(1);
                    cartUtil.addCart(gid, goodVO);
                }
                session.removeAttribute(UserServlet.CART);
                session.setAttribute(UserServlet.CART, cartUtil);
                url = "/WEB-INF/page/cart.jsp";
                List<GoodVO> list = cartUtil.getCart();
                request.setAttribute("cart", list);
                request.getRequestDispatcher(url).forward(request, response);
                break;
            case "getMyCart"://获取我的购物车列表
                url = "/WEB-INF/page/cart.jsp";
                List<GoodVO> list1 = cartUtil.getCart();
                request.setAttribute("cart", list1);
                request.getRequestDispatcher(url).forward(request, response);
                break;
            default:
                out.println("invalid mark");

        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
